package edu.pku.sei.modeler.handler;

import org.eclipse.gef.DragTracker;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.requests.CreateRequest;
import org.eclipse.gef.requests.CreationFactory;
import org.eclipse.gef.tools.SelectEditPartTracker;

/**
 * A creation drag tool understanding buttonPressed/buttonReleased.
 * Send a REQ_CREATE to the EditPart issuing the Tracker.
 * 
 * @author dumoulin
 * @todo Change the implementation to perform creation on buttonReleased event.
 */
public class CreationDragTool extends SelectEditPartTracker implements DragTracker {

	/**
	 * 
	 */
	protected CreationFactory factory;
	
	/**
	 * Constructor.
	 * 
	 * @param part 
	 * @param factory 
	 */
	public CreationDragTool( CreationFactory factory, EditPart part)
	{
		super(part);
		this.factory = factory;
	}
	
	
	/**
	 * 
	 * 
	 * @return 
	 * 
	 * @see org.eclipse.gef.tools.AbstractTool#getCommandName()
	 */
	@Override
	protected String getCommandName() {
		return REQ_CREATE;
	}

	/**
	 * 
	 * 
	 * @return 
	 * 
	 * @see org.eclipse.gef.tools.AbstractTool#getDebugName()
	 */
	@Override
	protected String getDebugName() {
		return "Creation Drag Tool";
	}

	/**
	 * Returns the creation factory used to create the new EditParts.
	 * 
	 * @return the creation factory
	 */
	protected CreationFactory getFactory() {
		return factory;
	}

	/**
	 * Creates a {@link CreateRequest} and sets this tool's factory on the request.
	 * 
	 * @return 
	 * 
	 * @see org.eclipse.gef.tools.TargetingTool#createTargetRequest()
	 */
	@Override
	protected Request createTargetRequest() {
		CreateRequest request = new CreateRequest();
		request.setFactory(getFactory());
		return request;
	}

	
	/**
	 * 
	 */
	@Override
	protected void performSelection() {
		if (hasSelectionOccurred()) {
			return;
		}
		resetFlags();
		setFlag(FLAG_SELECTION_PERFORMED, true);
		setCurrentCommand (getCommand());
		executeCurrentCommand();
	}

	/**
	 * 
	 * 
	 * @return 
	 */
	@Override
	protected Command getCommand() {
//		System.out.println(this.getTargetRequest().getType());
	    return getSourceEditPart().getCommand(getTargetRequest());
	}


    /**
     * 
     * 
     * @param button 
     * 
     * @return 
     */
    @Override
	protected boolean handleButtonDown (int button) {
        return super.handleButtonDown (button);
    }

    /**
     * 
     * 
     * @param button 
     * 
     * @return 
     */
    @Override
	protected boolean handleButtonUp(int button) {
		if (isInState(STATE_DRAG)) {
			performSelection();
			if ((button == 1) && (getSourceEditPart().getSelected() != EditPart.SELECTED_NONE)) {
				getCurrentViewer().reveal(getSourceEditPart());
			}
			setState(STATE_TERMINAL);
			return true;
		}
		return false;
	}

	
}
